// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({env: 'test-qch4n'})
const db = cloud.database({env: 'test-qch4n'})
// 云函数入口函数
exports.main = async (event, context) => {
  // let { OPENID, APPID, UNIONID } = cloud.getWXContext()
  let { longitude, latitude, page = 1, pages = 100 } = event
  // 先取出集合记录总数
  const { total = 0 } = await db.collection('warnList').where({
    status: 0
  }).count()
  // 计算需分几次取
  const batchTimes = Math.ceil(total / pages)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('warnList').where({
      status: 0,
      location: db.command.geoNear({
        geometry: db.Geo.Point(longitude, latitude)
      })
    })
    .skip(i * pages)
    .limit(pages)
    .get()
    tasks.push(promise)
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}